<style scoped>
    .com_top .inp{
        width:180px;
    }
    .el-table .disabled-row {
        background: oldlace;
    }
    .model_assets_list .btns{
        border-top:solid 1px #eee;
        padding:35px 0 0;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: center;
    }
    .model_assets_list .ml{
        margin-left:20px;
    }
    .model_assets_list .common_pages{
        justify-content: flex-start;
    }
    .assets_item_list:not(:last-child){
        border-bottom:solid 1px #eee;
        padding-bottom:5px;
        margin-bottom:5px;
    }
    .assets_item_list.first{
        border-bottom:none;
        padding-bottom:0px;
        margin-bottom:0px;
    }
    .assets_item_item{
        font-size:12px;
        display: flex;
        flex-direction: row;
        align-items: center;
    }
    .assets_item_item .as_1{
        display: inline-block;
        width:220px;
    }
    .assets_item_item .as_2{
        display: inline-block;
        width:150px;
    }
    .model_assets_list .b_t{
        padding-top:15px;
        border-top:solid 1px #eee; 
    }
</style>
<div class="content" id="team" v-cloak>
    <el-row>
        <el-col :span="12">
            <div class="grid-content bg-purple com_title">应用管理</div>
        </el-col>
    </el-row>
    <div class="com_top">
        <el-select v-model="environ_code" class="inp" @change="getList" placeholder="部署环境筛选">
            <el-option v-for="item in environlist" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
        </el-select>
        <el-select v-model="team_code" class="inp" @change="getList" placeholder="所属团队筛选">
            <el-option v-for="item in teamlist" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
        </el-select>
        <el-select v-model="net_type" class="inp" @change="getList" placeholder="部署网络方式筛选">
            <el-option v-for="item in netoption" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
        </el-select>
        <el-select v-model="status" class="inp" @change="getList" placeholder="应用状态筛选">
            <el-option v-for="item in statusopction" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
        </el-select>
        <el-input v-model="app_name" class="inp ml20" placeholder="按应用名称查询"></el-input>
        <el-button @click="getList" type="primary" >搜索</el-button>
    </div>
    <!-- table -->
    <div class="com_table_block mt20">
        <div class="table_header">
            <div class="l">应用管理</div>
            <div class="r">
                <el-button type="primary" size="medium" class="ml20" icon="el-icon-plus" @click="handleApplication(1)">新增应用</el-button>
            </div>
        </div>
        <div class="table_body">
            <el-table :data="datalist" style="width: 100%" :row-class-name="tableRowClassName">
                <el-table-column prop="name" label="应用名称" width="180">
                </el-table-column>
                <el-table-column label="所属团队" width="120">
                    <template slot-scope="scope">
                        <div>{{scope.row.teamlist[0]?scope.row.teamlist[0].name:''}}</div>
                    </template>
                </el-table-column>
                <el-table-column label="所属环境" width="100">
                    <template slot-scope="scope">
                        <div class="success">{{scope.row.environlist[0]?scope.row.environlist[0].name:''}}</div>
                    </template>
                </el-table-column>
                <el-table-column label="拥有资产" width="510">
                    <template slot-scope="scope">
                        <div class="assets_item_list" 
                            :class="{'first':scope.row.assets_list.length==1?true:false}"
                            v-for="(item,index) in scope.row.assets_list" 
                            :key="index">
                            <div class="assets_item_item" >
                                <span class="as_1">资产名称：{{item.name}}</span>
                                <span class="as_2" v-if="scope.row.net_type==1?true:false">外网IP：{{item.outer_ip}}</span>
                                <span class="as_2" v-if="scope.row.net_type==2?true:false">内网IP：{{item.lan_ip}}</span>
                                <el-button type="primary" size="small" @click="buildApplication(scope.row,item)" plain>单机部署</el-button>
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="user_name" label="操作人" width="80">
                </el-table-column>
                <el-table-column label="部署网络方式" width="120">
                    <template slot-scope="scope">
                        <div>{{scope.row.net_type == 1?'外网IP':'内网IP'}}</div>
                    </template>
                </el-table-column>
                <el-table-column label="可用状态" width="100">
                    <template slot-scope="scope">
                        <div v-if="scope.row.status == 1" class="success">已启用</div>
                        <div v-if="scope.row.status != 1" class="red">已禁用</div>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="320" fixed="right">
                    <template slot-scope="scope">
                        <div class="mb10">
                            <el-button @click="buildApplication(scope.row)" type="primary" size="small">快速部署</el-button>
                            <el-button @click="setAppConfig(scope.row)" type="success" size="small" plain>构建配置</el-button>
                            <el-button @click="handleApplication(2,scope.row)" type="primary" size="small">编辑</el-button>
                        </div>
                        <div class="mb10">
                            <el-button @click="distAsstes(scope.row)" type="success" size="small" plain>分配资产</el-button>
                            <el-button @click="distEmails(scope.row)" type="warning" size="small" plain>分配邮件</el-button>
                            <el-button @click="hanleDelete(scope.row)" type="danger" size="small">删除</el-button>
                        </div>
                        <div>
                            <el-button @click="applicationConsole(scope.row)" type="primary" size="small">控制台</el-button>
                            <el-button @click="serverConfigs(scope.row)" type="primary" size="small" plain>脚本任务</el-button>
                            <el-button v-if="scope.row.status==1?true:false" @click="hanleUse(scope.row)" type="danger" size="small" plain>禁用
                            </el-button>
                            <el-button v-if="scope.row.status==0?true:false" @click="hanleUse(scope.row)" type="success" size="small">启用</el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="common_pages">
            <el-pagination background @current-change="handleCurrentChange"
                :current-page.sync="currentPage" :page-size="pageSize" layout="prev, pager, next, jumper"
                :total="totalCount">
            </el-pagination>
        </div>
    </div>
    <!-- model弹出框 -->
    <el-dialog width="500px" title="应用编辑" :visible.sync="dialogTableVisible">
        <div class="com_model_main">
            <div class="com_model_block">
                <div class="left">所属团队<span class="red">*</span></div>
                <el-select class="inp" v-model="team.team_code" placeholder="请选择">
                    <el-option v-for="item in teamlist" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
            </div>
            <div class="com_model_block">
                <div class="left">选择环境<span class="red">*</span></div>
                <el-select class="inp" v-model="team.environ_code" placeholder="请选择">
                    <el-option v-for="item in environlist" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
            </div>
            <div class="com_model_block">
                <div class="left">应用名称<span class="red">*</span></div>
                <el-input class="inp" v-model="team.name" placeholder="请输应用名称"></el-input>
            </div>
            <div class="com_model_block">
                <div class="left">应用编码<span class="red">*</span></div>
                <el-input class="inp" v-model="team.code" placeholder="以app_开头、例如app_zxhy" :disabled="team.type==2?true:false"></el-input>
            </div>
            <div class="com_model_block">
                <div class="left">启用状态</div>
                <el-switch v-model="team.status" active-color="#409EFF"></el-switch>
            </div>
            <div class="btns">
                <el-button type="primary" @click="submitApplication"> 提交 </el-button>
            </div>
        </div>
    </el-dialog>
    <!-- 分配资产 -->
    <el-dialog width="950px" class="model_assets_list" title="分配资产" :visible.sync="assets.dialogAppVisible">
        <el-table :data="assets.assestsList" ref="multipleTable" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column property="name" label="所属团队" width="150"></el-table-column>
            <el-table-column property="name" label="资产名称" width="150"></el-table-column>
            <el-table-column property="code" label="资产编码" width="150"></el-table-column>
            <el-table-column property="outer_ip" label="外网IP" width="200"></el-table-column>
            <el-table-column property="lan_ip" label="内网IP" width="200"></el-table-column>
        </el-table>
        <div class="common_pages">
            <el-pagination background @current-change="handleAssetsCurrentChange" :current-page.sync="assets.currentPage"
                :page-size="assets.pageSize" layout="prev, pager, next, jumper" :total="assets.totalCount">
            </el-pagination>
        </div>
        <div class="com_model_block b_t">
            <div class="left">网络部署方式</div>
            <el-select class="inp" v-model="assets.net_type" placeholder="请选择">
                <el-option v-for="item in netoption" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
        </div>
        <div class="btns">
            <el-button type="primary" @click="submitAppsAssets">确定</el-button>
            <el-button class="ml" @click="assets.dialogAppVisible=false">取消</el-button>
        </div>
    </el-dialog>
    <!-- 分配邮件 -->
    <el-dialog width="700px" class="model_assets_list" title="分配邮件" :visible.sync="email.dialogEmailVisible">
        <el-table :data="email.emailsList">
            <el-table-column property="email" label="邮件地址" width="200"></el-table-column>
            <el-table-column property="name" label="邮件所属人" width="200"></el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button v-if="!scope.row.selected" @click="handleEmails(1,scope.row)" type="primary" size="small">绑定</el-button>
                    <el-button v-if="scope.row.selected" @click="handleEmails(2,scope.row)" type="danger" size="small" plain>取消</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="common_pages">
            <el-pagination background @current-change="handleAssetsCurrentChange" :current-page.sync="assets.currentPage"
                :page-size="assets.pageSize" layout="prev, pager, next, jumper" :total="assets.totalCount">
            </el-pagination>
        </div>
    </el-dialog>
</div>
<script>
    new Vue({
        el: '#team',
        data: function () {
            return {
                team_code:'',
                environ_code:'',
                net_type:'',
                app_name:'',
                status:'',
                teamlist: [],
                environlist:[],
                datalist: [],
                pageSize: 30,
                totalCount: 0,
                currentPage: 1,
                dialogTableVisible: false,
                type: 1,
                team: {
                    team_code:'',
                    environ_code:'',
                    type: 1,
                    _id: '',
                    name: '',
                    code: '',
                    status: true,
                },
                assets:{
                    net_type:1,
                    appItem:{},
                    dialogAppVisible: false,
                    multipleSelection: [],
                    assestsList: [],
                    currentPage: 1,
                    pageSize:10,
                    totalCount: 0,
                },
                netoption: [{
                    value: 1,
                    label: '外网IP'
                }, {
                    value: 2,
                    label: '内网IP'
                }],
                statusopction: [{
                    value: 1,
                    label: '启用'
                }, {
                    value: 0,
                    label: '禁用'
                }],
                email:{
                    dialogEmailVisible:false,
                    emailsList: [],
                    emailItem: [],
                    appId:'',
                    currentPage: 1,
                    pageSize: 10,
                    totalCount: 0,
                },
            }
        },
        filters: {
        },
        mounted() {
            this.getList();
            this.getTeamList();
            this.getEnvironList();
            this.getAssestList();
            this.getEmailList();
        },
        methods: {
            getList() {
                util.ajax({
                    type: 'get',
                    url: `${config.baseApi}api/v1/application/list`,
                    data: {
                        team_code: this.team_code,
                        environ_code:this.environ_code,
                        net_type:this.net_type,
                        status:this.status,
                        app_name:this.app_name,
                        pageNo: this.currentPage,
                        pageSize: this.pageSize,
                    },
                    success: data => {
                        this.totalCount = data.data.totalNum;
                        this.datalist = data.data.datalist;
                    }
                })
            },
            getTeamList() {
                util.ajax({
                    type: 'get',
                    url: `${config.baseApi}api/v1/team/list`,
                    data:{
                        pageNo:1,
                        pageSize:100,
                        status:1,
                    },
                    success: data => {
                        const datas = data.data.datalist || [];
                        const options = [];
                        datas.forEach(item=>{
                            options.push({
                                value: item.code,
                                label: item.name
                            })
                        })
                        this.teamlist = options;
                    }
                })
            },
            getEnvironList() {
                util.ajax({
                    type: 'get',
                    url: `${config.baseApi}api/v1/environment/list`,
                    data: {
                        pageNo: 1,
                        pageSize: 100,
                    },
                    success: data => {
                        const datas = data.data.datalist || [];
                        const options = [];
                        datas.forEach(item => {
                            options.push({
                                value: item.code,
                                label: item.name
                            })
                        })
                        this.environlist = options;
                    }
                })
            },
            getAssestList(){
                util.ajax({
                    type: 'get',
                    url: `${config.baseApi}api/v1/assets/list`,
                    data: {
                        status: 1,
                        pageNo: this.assets.currentPage,
                        pageSize: this.assets.pageSize,
                    },
                    success: data => {
                        this.assets.totalCount = data.data.totalNum;
                        this.assets.assestsList = data.data.datalist;
                    }
                })
            },
            distAsstes(item){
                this.assets.appItem = item;
                this.assets.dialogAppVisible = true;
                const assets_list = item.assets_list || [];
                this.assets.multipleSelection = assets_list;
                if(assets_list.length) {
                    this.assets.assestsList.forEach(item_1=>{
                        assets_list.forEach(item_2=>{
                            if(item_1.code === item_2.code){
                                setTimeout(()=>{ this.$refs.multipleTable.toggleRowSelection(item_1, true); },100)
                            }
                        })
                    })
                }
                this.$refs.multipleTable && this.$refs.multipleTable.clearSelection();
            },
            handleSelectionChange(val) {
                this.assets.multipleSelection = val;
            },
            handleAssetsCurrentChange(){
                this.assets.currentPage = val;
                this.getAssestList();
            },
            submitAppsAssets(){
                const assets_list = [];
                util.ajax({
                    url: `${config.baseApi}api/v1/application/distribution`,
                    data: {
                        _id: this.assets.appItem._id,
                        assets_list: this.assets.multipleSelection,
                        net_type:this.assets.net_type,
                    },
                    success: data => {
                        this.assets.dialogAppVisible = false;
                        this.getList();
                    }
                })
            },
            submitApplication() {
                if (!this.team.team_code) {
                    popup.alert({ title: '请选择所属团队!' });
                    return;
                }
                if (!this.team.environ_code) {
                    popup.alert({ title: '请选择所属环境!' });
                    return;
                }
                if (!this.team.name) {
                    popup.alert({ title: '请填写应用名称!' });
                    return;
                }
                if (!this.team.code) {
                    popup.alert({ title: '请填写应用编码!' });
                    return;
                }
                this.team.status = this.team.status ? 1 : 0;
                const userMsg = util.getStorage('local', 'userMsg');
                this.team.user_name = userMsg ? JSON.parse(userMsg).user_name : '';
                util.ajax({
                    url: `${config.baseApi}api/v1/application/handle`,
                    data: this.team,
                    success: data => {
                        this.dialogTableVisible = false;
                        this.getList();
                        popup.miss({ title: '操作成功!' });
                    }
                })
            },
            handleApplication(type, item) {
                if (item) item = JSON.parse(JSON.stringify(item));
                if (item) {
                    this.team = {
                        team_code: item.team_code,
                        environ_code: item.environ_code,
                        type: item.type,
                        _id: item._id,
                        name: item.name,
                        code: item.code,
                        status: item.status == 1 ? true : false,
                    };
                } else {
                    this.team = {
                        team_code: '',
                        environ_code:'',
                        type: 1,
                        _id: '',
                        name: '',
                        code: 'app_' + util.randomString(12),
                        status: true,
                    }
                }
                this.team.type = type;
                this.dialogTableVisible = true;
            },
            handleCurrentChange(val) {
                this.currentPage = val;
                this.getList();
            },
            hanleUse(item) {
                let str = item.status == 1 ? '禁用' : '启用';
                popup.confirm({
                    title: `确定${str}${item.name}应用吗？`, yes: () => {
                        util.ajax({
                            url: `${config.baseApi}api/v1/application/setStatus`,
                            data: {
                                _id: item._id,
                                status: item.status == 1 ? 0 : 1,
                            },
                            success: data => {
                                item.status = item.status == 1 ? 0 : 1,
                                    popup.miss({ title: '操作成功!' });
                            }
                        })
                    }
                })
            },
            hanleDelete(item) {
                popup.confirm({
                    title: `确定删除${item.name}应用吗？`, yes: () => {
                        util.ajax({
                            url: `${config.baseApi}api/v1/application/delete`,
                            data: {
                                _id: item._id,
                            },
                            success: data => {
                                this.getList();
                                popup.miss({ title: '操作成功!' });
                            }
                        })
                    }
                })
            },
            tableRowClassName({ row, rowIndex }) {
                if (row.status != 1) {
                    return 'disabled-row';
                }
                return '';
            },
            setAppConfig(item){
               location.href = "/appconfig?id=" + item._id;
            },
            getEmailList(){
                util.ajax({
                    type: 'get',
                    url: `${config.baseApi}api/v1/email/list`,
                    data:{
                        status: 1,
                        pageNo: this.email.currentPage,
                        pageSize:this.email.pageSize,
                    },
                    success: data => {
                        this.email.totalCount = data.data.totalNum;
                        this.email.emailsList = data.data.datalist;
                    }
                })
            },
            distEmails(item){
                 const itemEmailList = item.email_list || [];
                this.email.emailItem = itemEmailList;
                this.email.appId = item._id;
                this.email.dialogEmailVisible = true;
                const emailsList = this.email.emailsList;
                emailsList.forEach(item=>{
                    item.selected = false;
                    if(itemEmailList.includes(item.email)){
                        item.selected = true;
                    }
                })
                this.email.emailsList = emailsList;
            },
            handleEmails(type,item){
                if(type === 1){
                    // 绑定
                    this.email.emailItem.push(item.email);
                }else if(type === 2){
                    // 取消
                    const index = this.email.emailItem.indexOf(item.email);
                    this.email.emailItem.splice(index,1)
                }
                util.ajax({
                    url: `${config.baseApi}api/v1/application/handleEmail`,
                    data:{
                        id: this.email.appId,
                        emaillist: this.email.emailItem,
                    },
                    success:data=>{
                        this.email.dialogEmailVisible = false;
                        this.getList();
                        popup.miss({title:'操作成功!'})
                    }
                })
            },
            buildApplication(item,assetsItem){
                if(!item.task_list || !item.task_list.length){
                    popup.alert({ title: '请先增加应用构建配置!' })
                    return
                }
                let url = '/buildprocess?id=' + item._id;
                if(assetsItem) url = url + '&assetsId=' + assetsItem._id;
                location.href = url;
            },
            applicationConsole(item){
                if (!item.assets_list || !item.assets_list.length) {
                    popup.alert({ title: '请先给应用分配资产!' })
                    return
                }
                let ids = '';
                item.assets_list && item.assets_list.forEach(item=>{
                    ids = ids + item._id + ','
                })
                ids = ids ? ids.slice(0,-1) : '';
                window.open("/console?ids=" + ids);
            },
            serverConfigs(item) {
                if(!item.assets_list || !item.assets_list.length) {
                    popup.alert({title:'请先给应用分配资产!'})
                    return
                }
                util.setStorage('session', 'assets_list_configs', JSON.stringify(item.assets_list));
                location.href = "/assetsconfig";
            },
        }
    })
</script>